let isUndef = (val) => typeof val === "undefined"
let isString = (val) => typeof val === "string"
let isNull = (val) => val === null
let isEmptyString = (val) => (val || "").trim() === ""

export default {
  methods: {
    $$throwError(err) {
      throw new Error(err)
    },

    $$showError(err) {
      this.$notify.warning({
        title: "消息",
        message: `${err}不能为空`,
      })
    },

    /**
     * 校验表格
     */
    $$validateForm(data, arr, arrProp) {
      let ret = true
      // let arrTypeProps = arr
      //   .filter((item) => item.type === Array)
      //   .map((item) => item.prop)
      let len = arr.length
      const arrTypeProps = arrProp || []

      // 跳出循环
      let breakLoop = () => this.$$throwError("validateError")

      try {
        data.forEach((item, index) => {
          arr.forEach(({ prop, label }) => {
            let val = item[prop]
            if (arrTypeProps.includes(prop) && val.length === 0) {
              this.$$showError(label, index)
              breakLoop()
            }
            if (isUndef(val)) {
              this.$$showError(label, index)
              breakLoop()
            }
            if (isNull(val)) {
              this.$$showError(label, index)
              breakLoop()
            }
            let isUnValid = isString(val) && isEmptyString(val)
            if (isUnValid) {
              this.$$showError(label, index)
              breakLoop()
            }
          })
        })
      } catch (error) {
        // console.log('子表验证错误: ')
        // console.log(error)
        ret = false
      }

      return ret
    },

    /**
     * 校验表单
     */
    $validateForm(data, all, arrProp) {
      let ret = true
      let f = data
      let len = all.length
      const arrTypeProps = arrProp || []
      let showError = (err) => {
        this.$notify.warning({
          title: "消息",
          message: err + "不能为空",
        })
      }
      for (let index = 0; index < len; index++) {
        const item = all[index]
        let { prop, label } = item
        let val = f[prop]
        if (arrTypeProps.includes(prop)) {
          if (val.length === 0) {
            showError(label)
            ret = false
            break
          }
        } else if (typeof val === "undefined") {
          showError(label)
          ret = false
          break
        } else if (val === null) {
          showError(label)
          ret = false
          break
        } else {
          let isUnValid = typeof val === "string" && (val || "").trim() === ""
          if (isUnValid) {
            showError(label)
            ret = false
            break
          }
        }
      }
      return ret
    },
  },
}
